jQuery(function() {
//获取选中状态
	$(function(){
		  $(":radio").click(function(){
			  //jQuery('#keyword').val('');
			  serverData.key = jQuery('#keyword').val();;
			  var isSubmit=$('input:radio[name="isReceived"]:checked').val();
			  serverData.isSubmit = isSubmit;
			  serverTable.draw();
		  });
	});

var serverData = {};
serverData.key = '';
var isSubmit= $('input:radio[name="isReceived"]:checked').val();
serverData.isSubmit=isSubmit;
var serverTable;
jQuery(document).ready(function() {
					serverTable = jQuery('#inHouseTable').DataTable(
									{
										"serverSide" : true,
										"ordering" : false,
										"ajax" : {
											"dataType" : "json",
											"type" : "get",
											"cache" : false,
											"url" : window.rootPath
													+ '/ui/afterSaleInHouse/getpage',
											"data" : function(d) {
												return $.extend({}, d,
														serverData);
											}
										},
						columns : [
							{
			                	data: null,
			                	defaultContent: ""
			                },
			                {
			                    data: null,
			                    defaultContent: "",
			                    render: function (data, type, full, meta) {
			                        var operate =' <input type="checkbox" class="checkchild" />';
			                        return operate;

			                    }
			                },
			                {
			                	data: null,
			                	 render: function (data, type, full, meta) {
				                        var dOut;
				                        if(data.isSubmit=="0"){
				                            dOut = '<td class="center" ><span class="badge label-pill label-danger">未提交</span></td>';
				                        }     
				                        else if(data.isSubmit=="1") {
				                            dOut = '<td class="center" ><span class="badge label-pill label-danger">退回</span></td>';
				                        }   
				                        else if(data.isSubmit=="2") {
				                            dOut = '<td class="center" ><span class="badge label-pill label-primary">已提交</span></td>';
				                        } 
				                        else if(data.isSubmit=="3") {
				                            dOut = '<td class="center" ><span class="badge label-pill label-primary">已派遣</span></td>';
				                        } 
				                        else if(data.isSubmit=="4") {
				                            dOut = '<td class="center" ><span class="badge label-pill label-primary">跟踪中</span></td>';
				                        } 
				                        else if(data.isSubmit=="5") {
				                            dOut = '<td class="center" ><span class="badge label-pill label-primary">待回访</span></td>';
				                        } 
				                        else if(data.isSubmit=="6") {
				                            dOut = '<td class="center" ><span class="badge label-pill label-success">已完成</span></td>';
				                        }
				                        return dOut;
				                    }
			                },
			                {
			                    data: 'manageCode'
			                },
			                {
			                    data: 'contractCode',
				                render:function(data,type,full,meta){
				                	if(data == null || data == undefined || data == ""){
										return data;
									}else{
										return (data.length > 7) ? '<font title="'+data+'">'+data.substring(0,7)+'...'+'</font>' : data;
									}
								}
			                },
			                {
			                    data: 'unitName',
				                render:function(data,type,full,meta){
				                	if(data == null || data == undefined || data == ""){
										return data;
									}else{
										return (data.length > 7) ? '<font title="'+data+'">'+data.substring(0,7)+'...'+'</font>' : data;
									}
								}
			                },
			                {
			                	data:'deviceNumber',
				                render:function(data,type,full,meta){
				                	if(data == null || data == undefined || data == ""){
										return data;
									}else{
										return (data.length > 7) ? '<font title="'+data+'">'+data.substring(0,7)+'...'+'</font>' : data;
									}
								}
			                },
			                {
			                	data:'afterSaleType'
			                },
			                {
			                	data: 'questionDetail',
				                render:function(data,type,full,meta){
				                	if(data == null || data == undefined || data == ""){
										return data;
									}else{
										return (data.length > 18) ? '<font title="'+data+'">'+data.substring(0,18)+'...'+'</font>' : data;
									}
								}
			                },
			                {
			                	data:'serviceTime',
			                	render: function (data, type, full, meta) {
			                            if (data)
			                                return moment(data).format('YYYY/MM/DD');
			                            else
			                                return '';
			                     }
			                },
			                {
			                	data:'proposer'
			                },
			                {
			                	data:'superior'
			                },
			                {
			                	data:'createTime',
			                	render: function (data, type, full, meta) {
		                            if (data)
		                                return moment(data).format('YYYY/MM/DD');
		                            else
		                                return '';
		                       }
			                },
			                {
			                	data:'linkMan'
			                },
			                {
			                	data:'linkManPhone'
			                }
			                /*{
		                	    data: 'ticketState',
		                	    render : function(data,type, full,meta) {
									var dOut;
									if (data == '审批中') {
										dOut = '<td class="center" ><span class="badge label-pill label-primary">审批中</span></td>';
									} else if (data == '驳回') {
										dOut = '<td class="center" ><span class="badge label-pill label-danger">驳回</span></td>';
									} else if (data == '通过') {
										dOut = '<td class="center" ><span class="badge label-pill label-success">通过</span></td>';
									} else if (data == '未提交') {
										dOut = '<td class="center" ><span class="badge label-pill label-default">未提交</span></td>';
									} else if (data == '已提交') {
										dOut = '<td class="center" ><span class="badge label-pill label-warning">已提交</span></td>';
									}else if(data==null){
										dOut='';
									}
									return dOut;
								}
		                    },
			                {
			                	data:'submiter.empLogin.userName'
			                },
			                {
			                	data:'deviceCode'
			                },
			                {
			                	data:'deviceName',
				                render:function(data,type,full,meta){
				                	if(data == null || data == undefined || data == ""){
										return data;
									}else{
										return (data.length > 7) ? '<font title="'+data+'">'+data.substring(0,7)+'...'+'</font>' : data;
									}
								}
			                },*/
			               ],
						"drawCallback" : function(oSettings) {
											var k = 0;
											var total = oSettings.aiDisplay.length
													+ oSettings._iDisplayStart;
											for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
												$(
														'td:eq(0)',
														oSettings.aoData[oSettings.aiDisplay[k]].nTr)
														.text(i + 1);
												k++;
											}
										}
									});
					

				});
// 完善服务单
jQuery(".perfection").on('click',function() {
			var selects = getSelect("#inHouseTable", 1);
			if (selects.length > 1) {
				message('只能操作一条记录');
			} 
			else if (selects.length == 0) {
				message('请选择要操作的记录');
			} 
			else if (selects.length == 1) {
				var id = selects[0].id;
				var type = selects[0].afterSaleType;
				var isSubmit = selects[0].isSubmit;
				var ticketState = selects[0].ticketState;
				if(type=='三包办理'){
					if(ticketState== null || ticketState == '驳回'|| ticketState == '通过'){
						window.location = window.rootPath+ "/ui/afterSaleInHouse/perfection" + "?type="
								+ type + "&ticketId=" + id;
					}
					else{
						message('审批中不可操作！');
						return;
					}
				}else{
					if (isSubmit ==6) {
						message('已完成,服务单不可操作！');
						return;
					} else {
						window.location = window.rootPath+ "/ui/afterSaleInHouse/perfection" + "?type="
								+ type + "&ticketId=" + id;
					}				
				}
			}
		});

//退回服务单按钮
jQuery(".backTicket").on('click',function(){
	  var selects = getSelect("#inHouseTable", 1);
	  if (selects.length == 0) {
		  message('请选择要退回的服务单');
	  }
	  else if (selects.length >1){
		  message('只能选择退回一条服务单');
	  }
	  else if(selects.length==1){
		  var type = selects[0].afterSaleType;
		  var ticketState=selects[0].ticketState;
		  if(type=='三包办理'&&(ticketState== '已提交' || ticketState == '审批中'|| ticketState == '通过')){
				  message("三包审批中，或已经通过，不能退回");
		  }else{
			  if(selects[0].isSubmit>2){
				  message('已经派遣不能退回'); 
			  }
			  else{
				  $.springLemonDialog({
						content : '确定退回'+selects[0].unitName+selects[0].afterSaleType+"的申请",// 确认文本
						clickButton : function(sender, modal, index) {// 按钮事件处理
							if(index==0){
//								for(var i=0;i<selects.length;i++){
									var id=selects[0].id;
									var userId=selects[0].user.id;
									var d={
											"isSubmit":1
									}
									var url = window.rootPath + '/api/afterSaleTickets/'+id;
									jQuery.ajax({
										url : encodeURI(url),
										type : 'patch',
										data : JSON.stringify(d),
										dataType : 'json',
										contentType : 'application/json;charset=utf-8',
										success : function() {
											serverTable.draw(false);
											//插入待办任务
											addTask("售后申请退回","/ui/afterSaleTicket",userId,0,id)
											
										}
									});
//								}
							}
							$(this).closeDialog(modal);
						}
					});
			  }   
		  }
	  }
});
// 生成派遣单
jQuery(".createTicket").on('click', function() {
	var selects = getSelect("#inHouseTable", 1);
	if (selects.length > 1) {
		message('只能操作一条记录');
	} else if (selects.length == 0) {
		message('请选择要操作的记录');
	} else if (selects.length == 1) {
		var id = selects[0].id;
		if(selects[0].afterSaleType=='三包办理'){
			if (selects[0].ticketState != '通过') {
				message('该服务单尚未通过审批！')
				return;
			}
		}
		if(selects[0].isSubmit==6){
			message('该服务单已结完成，不能派遣！');
			return;
		}
		if (selects[0].manageCode == null) {
			message('该服务单尚未完善,请输入管理代码！');
		} else {
			$("#ticketId").val(id);
			$("#startTime").val('');
			$("#endTime").val('');
			$("#sender").select2().val(selects[0].user.id).trigger("change");
			$("#sendReason").val('');
			sendOutData.ticketId=id;
			sendOutTable.draw();
			jQuery("#sendOutHouseModal").modal('show');
			
		}

	}

});
// 派遣服务单保存
jQuery(".saveSendBtn").on('click',function() {
			if (jQuery("#sendOutHouseForm")&& !jQuery("#sendOutHouseForm").Validform({
						tiptype : 3,
						showAllError : true
					}).check(false)) {
				return;
			};
			var startTime1 = jQuery("#startTime").val();
      	    var endTime1 = jQuery("#endTime").val();
      	    var startDate = new Date(startTime1).getTime();
      	    var endDate = new Date(endTime1).getTime()
	          if(startDate>endDate){
	        	  message('开始时间不能大于结束时间');
	        	  return;
	          }
			jQuery(".saveSendBtn").attr("disabled", "disabled");
			var url = window.rootPath + '/ui/afterSaleOutHouse/save';
			var d = {
				"user" : {
					"id" : $("#sender").val()
				},
				"afterSaleTicket" : {
					"id" : $("#ticketId").val()
				},
				"startTime" : $("#startTime").val(),
				"endTime" : $("#endTime").val(),
				"sendReason" : $("#sendReason").val()
			}
			jQuery.ajax({
				url : encodeURI(url),
				type : 'post',
				data : JSON.stringify(d),
				dataType : 'json',
				contentType : 'application/json;charset=utf-8',
				success : function(data) {
					var taskId=data.outId;
					var userId=$("#sender").val();
					var url1 = window.rootPath + '/api/afterSaleTickets/'+ $("#ticketId").val();
					var d1 = {
							"isSubmit" : 3
					}
					jQuery.ajax({
						url : encodeURI(url1),
						type : 'patch',
						data : JSON.stringify(d1),
						dataType : 'json',
						contentType : 'application/json;charset=utf-8',
						success : function(data) {
							jQuery(".saveSendBtn").removeAttr("disabled");
							/*jQuery("#sendOutHouseModal").modal('hide');*/
							/*message('服务单派遣成功！')*/
							addTask("待办派遣单","/ui/afterSaleOutHouse",userId,0,taskId)
							serverTable.draw();
							sendOutData.ticketId=$("#ticketId").val();
							sendOutTable.draw();
						}

					});
				}

			});			
		});

////派遣单列表
var sendOutData = {};
sendOutData.ticketId = '';
var sendOutTable;
jQuery(document).ready(function() {
	sendOutTable = jQuery('#sendOutTable').DataTable(
									{
										"serverSide" : true,
										"ordering" : false,
										"iDisplayLength": 4,
										"ajax" : {
											"dataType" : "json",
											"type" : "get",
											"cache" : false,
											"url" : window.rootPath
													+ '/ui/afterSaleInHouse/getoutpage',
											"data" : function(d) {
												return $.extend({}, d,
														sendOutData);
											}
										},
						columns : [
							{
			                	data: null,
			                	defaultContent: ""
			                },
			                {
			                    data: 'afterSaleTicket.manageCode'
			                },
			                {
			                	data:'user.empLogin.userName'
			                },
			               
			                {
			                    data: null,
			                    defaultContent: "",
			                    render: function (data, type, full, meta) {
			                        var operate ='<button type="button" class="btn btn-sm btn-info delBtn">删除</button>';
			                        return operate;

			                    }
			                }
			               ],
						"drawCallback" : function(oSettings) {
											var k = 0;
											var total = oSettings.aiDisplay.length
													+ oSettings._iDisplayStart;
											for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
												$(
														'td:eq(0)',
														oSettings.aoData[oSettings.aiDisplay[k]].nTr)
														.text(i + 1);
												k++;
											}

											sendOutTable.off('click', 'tr');
											sendOutTable.on('click', 'tr', function (event) {
							                    event = event || window.event;
							                    var target = event.target || event.scrElement;
							                    var data = sendOutTable.row(this).data();
							                    if (target.className.indexOf('fa-remove') != -1 || target.className.indexOf('delBtn') != -1) {
							                        deleteOut(data);
							                    }
							                    return;
							                });
										}
									});

				});
///删除派遣单
function deleteOut(data){
	if (!data) return;
	var url =window.rootPath+ "/api/afterSaleOutHouses/" + data.id;
	var taskId=data.id;
    jQuery.ajax({
        url: encodeURI(url),
        cache: false,
        type: "delete",
        dataType: "json",
        success: function (data) {
        	sendOutData.ticketId=$("#ticketId").val();
			sendOutTable.draw();
			delTask(taskId,"待办派遣单")//删除待办任务
        }
    });
}
// 查看详情
jQuery(".detailBtn").on('click',function() {
			var selects = getSelect("#inHouseTable", 1);
			if (selects.length > 1) {
				$.springLemonDialog({
					content : '一次只能查看一条记录',// 确认文本
					clickButton : function(sender, modal, index) {// 按钮事件处理
						$(this).closeDialog(modal);
					}
				});
			} else if (selects.length == 0) {
				$.springLemonDialog({
					content : '请选择要查看的记录',// 确认文本
					clickButton : function(sender, modal, index) {// 按钮事件处理
						$(this).closeDialog(modal);
					}
				});
			} else if (selects.length == 1) {
				if (selects[0].isSubmit == 0) {
					$.springLemonDialog({
						content : '未提交的记录没有详情',// 确认文本
						clickButton : function(sender, modal, index) {// 按钮事件处理
							$(this).closeDialog(modal);
						}
					});
				} else {
					var id = selects[0].id;
					var afterSaleType = selects[0].afterSaleType;
					url = window.rootPath + "/ui/afterSaleTicket/ticketDetail"
							+ "?ticketId=" + id + "&afterSaleType="
							+ afterSaleType;
					window.location = url;
				}
			}
		});
// 查询
jQuery('.searchBtn').on('click', function() {
	serverData.key = jQuery('#keyword').val();
	var isSubmit=$('input:radio[name="isReceived"]:checked').val();
	serverData.isSubmit=isSubmit;
	serverTable.draw();
});
// 撤销查询
jQuery('.cancelBtn').on("click", function() {
	jQuery('#keyword').val('');
	//jQuery("#ticketState").val('');
	var isSubmit=$('input:radio[name="isReceived"]:checked').val();
	serverData.key = '';
	serverData.isSubmit=isSubmit;
	serverTable.draw();
});
/*jQuery('#ticketState').change(function(){
	serverData.key=jQuery("#keyword").val();
	var isSubmit=jQuery('#ticketState').val();
	serverData.isSubmit=isSubmit;
	serverTable.draw();
});*/
// /////列表中的全选
$("#checkAll").click(function() {
	var check = $(this).prop("checked");
	$(".checkchild").prop("checked", check);
});

// 察看三包审批
jQuery('.btn-audit-nodes').on('click',function() {
			var selects = getSelect("#inHouseTable", 1);
			if (selects.length < 1)
				return;
			if (selects[0].afterSaleType != '三包办理'){
				$.springLemonDialog({
					content : '该服务单不是三包服务单！',// 确认文本
					clickButton : function(sender, modal, index) {// 按钮事件处理
						$(this).closeDialog(modal);
					}
				});
				return;
			}
				
			if (selects[0].ticketState == '未提交') {
				alert(selects[0].contractCode + '还没有提交审批');
				return;
			}
			var url = window.rootPath
					+ '/ui/task/audit-nodes/afterSaleInHouse/' + selects[0].id;
			jQuery.get(encodeURI(url), null, function(html) {
				jQuery('#modal-audit-nodes-content').html(html);
				jQuery('#modal-audit-nodes').modal("show");
			});
		});
});
